package com.socialsoftware.Page;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.material.tabs.TabLayout;
import com.socialsoftware.R;
import com.socialsoftware.adapter.SearchResultAdapter;
import com.socialsoftware.api.ApiError;
import com.socialsoftware.api.ApiService;
import com.socialsoftware.model.Contact;
import com.socialsoftware.repository.ContactRepository;
import com.socialsoftware.repository.FriendRequestRepository;
import com.socialsoftware.util.SessionManager;
import com.socialsoftware.viewmodel.FriendRequestViewModel;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import com.google.gson.Gson;
/**
 * 添加好友页面
 * 应用程序的添加好友功能，包括搜索用户、扫描二维码、手机联系人
 */
public class AddFriendActivity extends AppCompatActivity implements SearchResultAdapter.OnResultClickListener {
    private static final String TAG = "AddFriendActivity";
    private static final int REQUEST_CONTACTS_PERMISSION = 100;
    private Toolbar toolbar;    // UI组件
    private EditText etSearch;
    private ImageView btnClearSearch;
    private RecyclerView recyclerViewResults;
    private LinearLayout emptyState;
    private LinearLayout addFriendMethods;
    private LinearLayout contactsSection;
    private ProgressBar progressBar;
    private TabLayout tabLayout;
    private TextView tvRequestCount;
    private SearchResultAdapter adapter;    // 数据
    private final List<Contact> searchResults = new ArrayList<>();
    private FriendRequestViewModel friendRequestViewModel;
    // 服务
    private ApiService apiService;
    private ContactRepository contactRepository;
    private SessionManager sessionManager;
    private FriendRequestRepository friendRequestRepository;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_friend);
        setStatusBar();// 设置状态栏
        sessionManager = SessionManager.getInstance(this);        // 初始化服务
        apiService = new ApiService(sessionManager);
        contactRepository = new ContactRepository(getApplication());
        friendRequestRepository = new FriendRequestRepository(getApplication());
        friendRequestViewModel = new ViewModelProvider(this).get(FriendRequestViewModel.class);// 初始化ViewModel
        initViews();// 初始化UI
        setupToolbar();
        setupSearchBar();
        setupRecyclerView();
        setupTabs();
        setupClickListeners();
        observeFriendRequestCount();// 观察好友请求数量
        friendRequestRepository.fetchPendingRequestsFromServer();// 从服务器获取最新的好友请求
    }
    
    private void initViews() {
        toolbar = findViewById(R.id.toolbar);
        etSearch = findViewById(R.id.et_search);
        btnClearSearch = findViewById(R.id.btn_clear_search);
        recyclerViewResults = findViewById(R.id.recycler_view_results);
        emptyState = findViewById(R.id.empty_state);
        addFriendMethods = findViewById(R.id.add_friend_methods);
        contactsSection = findViewById(R.id.contacts_section);
        progressBar = findViewById(R.id.progress_bar);
        tabLayout = findViewById(R.id.tab_layout);
        tvRequestCount = findViewById(R.id.tv_request_count);
        
        // 默认隐藏好友请求数量
        tvRequestCount.setVisibility(View.GONE);
    }
    
    private void setupToolbar() {
        // Set the toolbar as the support action bar
        setSupportActionBar(toolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setDisplayShowHomeEnabled(true);
            getSupportActionBar().setTitle("添加朋友");
        }
        
        toolbar.setNavigationOnClickListener(v -> onBackPressed());
    }
    
    private void setupSearchBar() {// 设置搜索框文本变化监听
        etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                btnClearSearch.setVisibility(s.length() > 0 ? View.VISIBLE : View.GONE);// 显示或隐藏清除按钮
            }
            @Override
            public void afterTextChanged(Editable s) {}
        });
        etSearch.setOnEditorActionListener((v, actionId, event) -> {// 设置搜索动作监听
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                String query = etSearch.getText().toString().trim();
                if (!TextUtils.isEmpty(query)) {
                    searchFriend(query);
                }
                return true;
            }
            return false;
        });
        
        // 清除按钮点击事件
        btnClearSearch.setOnClickListener(v -> {
            etSearch.setText("");
            showAddFriendMethods();
        });
    }
    
    private void setupRecyclerView() {
        adapter = new SearchResultAdapter(this, searchResults);
        adapter.setOnResultClickListener(this);
        recyclerViewResults.setLayoutManager(new LinearLayoutManager(this));
        recyclerViewResults.setAdapter(adapter);
    }
    
    private void setupTabs() {
        tabLayout.addTab(tabLayout.newTab().setText("账号"));
        tabLayout.addTab(tabLayout.newTab().setText("手机号"));
        tabLayout.addTab(tabLayout.newTab().setText("邮箱"));
        
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                updateSearchHint(tab.getPosition());
            }
            
            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                // 不需要处理
            }
            
            @Override
            public void onTabReselected(TabLayout.Tab tab) {
                // 不需要处理
            }
        });
        
        // 默认选中第一个标签
        updateSearchHint(0);
    }
    private void updateSearchHint(int tabPosition) {
        switch (tabPosition) {
            case 0:
                etSearch.setHint("账号/QQ号");
                break;
            case 1:
                etSearch.setHint("手机号");
                break;
            case 2:
                etSearch.setHint("邮箱地址");
                break;
        }
    }
    private void setupClickListeners() {

        findViewById(R.id.btn_scan_qr).setOnClickListener(v -> {// 扫一扫
            Intent intent = new Intent(this, QRScannerActivity.class);
            startActivity(intent);
        });
        findViewById(R.id.btn_contacts).setOnClickListener(v -> {// 手机联系人
            // 直接显示联系人同步页面，无论权限状态如何
            showContactsAndRequestPermission();
        });
        // 公众号
        findViewById(R.id.btn_official_accounts).setOnClickListener(v -> {
            Toast.makeText(this, "打开公众号", Toast.LENGTH_SHORT).show();
            // TODO: 实现公众号搜索功能
        });
        
        // 雷达加朋友
        findViewById(R.id.btn_radar).setOnClickListener(v -> {
            Toast.makeText(this, "雷达加朋友", Toast.LENGTH_SHORT).show();
            // TODO: 实现雷达加朋友功能
        });
        
        // 面对面建群
        findViewById(R.id.btn_face_to_face).setOnClickListener(v -> {
            Toast.makeText(this, "面对面建群", Toast.LENGTH_SHORT).show();
            // TODO: 实现面对面建群功能
        });
        
        // 好友请求
        findViewById(R.id.btn_friend_requests).setOnClickListener(v -> {
            // 打开好友请求页面
            Intent intent = new Intent(this, FriendRequestsActivity.class);
            startActivity(intent);
        });
    }
    
    /**
     * 观察好友请求数量
     */
    private void observeFriendRequestCount() {
        LiveData<Integer> pendingRequestsCount = friendRequestViewModel.getPendingRequestsCount();
        if (pendingRequestsCount != null) {
            pendingRequestsCount.observe(this, count -> {
                if (count != null && count > 0) {
                    tvRequestCount.setVisibility(View.VISIBLE);
                    tvRequestCount.setText(String.valueOf(count));
                } else {
                    tvRequestCount.setVisibility(View.GONE);
                }
            });
        } else {
            // 如果LiveData为null，隐藏请求数量显示
            tvRequestCount.setVisibility(View.GONE);
        }
    }
    
    /**
     * 直接显示联系人同步页面，并在必要时请求权限
     * 这是一个强制性实现，确保即使权限处理有问题也能打开联系人同步
     */
    private void showContactsAndRequestPermission() {
        // 首先显示联系人页面
        showContactsSection();
        
        // 显示模拟数据，同时在后台请求权限
        showMockContactsData();
        
        // 如果没有权限，尝试请求权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS)
                != PackageManager.PERMISSION_GRANTED) {
            try {
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.READ_CONTACTS},
                        REQUEST_CONTACTS_PERMISSION);
            } catch (Exception e) {
                Log.e(TAG, "请求权限时发生错误", e);
            }
        }
    }
    
    /**
     * 显示模拟联系人数据
     */
    private void showMockContactsData() {
        LinearLayout loadingLayout = findViewById(R.id.contacts_loading_layout);
        RecyclerView recyclerViewContacts = findViewById(R.id.recycler_view_contacts);
        LinearLayout emptyContactsState = findViewById(R.id.empty_contacts_state);
        loadingLayout.setVisibility(View.VISIBLE);// 先显示加载状态
        recyclerViewContacts.setVisibility(View.GONE);
        emptyContactsState.setVisibility(View.GONE);
        new Handler().postDelayed(() -> {// 延迟1.5秒后显示空状态（模拟加载过程）
            loadingLayout.setVisibility(View.GONE); // 显示空状态页面
            recyclerViewContacts.setVisibility(View.GONE);
            emptyContactsState.setVisibility(View.VISIBLE);
        }, 15000);
    }
    /**
     * 搜索好友
     * @param query 搜索关键词（账号/手机号/邮箱）
     */
    private void searchFriend(String query) {
        Log.d(TAG, "搜索好友: " + query);// 显示加载状态
        showLoading();
        String searchType;        // 根据当前选中的标签确定搜索类型
        switch (tabLayout.getSelectedTabPosition()) {
            case 1:
                searchType = "phone";
                break;
            case 2:
                searchType = "email";
                break;
            case 0:
            default:
                searchType = "account_id";
                break;
        }
        
        // 调用API搜索用户
        apiService.searchFriends(query, searchType, new ApiService.ApiCallback<List<Contact>>() {
            @Override
            public void onSuccess(List<Contact> results) {
                runOnUiThread(() -> {
                    // 更新搜索结果
                    searchResults.clear();
                    if (results != null && !results.isEmpty()) {
                        searchResults.addAll(results);
                        showSearchResults();
                    } else {
                        showEmptyState();
                    }
                    adapter.notifyDataSetChanged();
                });
            }
            
            @Override
            public void onFailure(ApiError error) {
                runOnUiThread(() -> {
                    Log.e(TAG, "搜索好友失败: " + error.getMessage());
                    
                    // 如果API请求失败，使用模拟数据
                    searchResults.clear();
                    
                    // 根据搜索关键词创建模拟数据
                    if (query.equals("test") || query.equals("123456") || 
                        query.equals("13800138000") || query.equals("test@example.com")) {
                        
                        // 创建一个模拟联系人
                        Contact mockContact = new Contact(
                                searchType.equals("phone") ? "13800138000" : 
                                searchType.equals("email") ? "test@example.com" : "wxid_test123",
                                "用户_" + query,
                                "avatar_default");
                        mockContact.setRegion("北京");
                        searchResults.add(mockContact);
                        
                        // 再添加一个模拟联系人
                        Contact mockContact2 = new Contact(
                                searchType.equals("phone") ? "13900139000" : 
                                searchType.equals("email") ? "test2@example.com" : "wxid_test456",
                                "测试用户_" + System.currentTimeMillis() % 1000,
                                "avatar_default");
                        mockContact2.setRegion("上海");
                        searchResults.add(mockContact2);
                        
                        showSearchResults();
                    } else {
                        showEmptyState();
                    }
                    
                    adapter.notifyDataSetChanged();
                    
                    // 显示错误提示
                    Toast.makeText(AddFriendActivity.this, 
                            "搜索失败: " + error.getMessage(), 
                            Toast.LENGTH_SHORT).show();
                });
            }
        });
    }
    
    /**
     * 显示加载状态
     */
    private void showLoading() {
        progressBar.setVisibility(View.VISIBLE);
        recyclerViewResults.setVisibility(View.GONE);
        emptyState.setVisibility(View.GONE);
        addFriendMethods.setVisibility(View.GONE);
        contactsSection.setVisibility(View.GONE);
    }
    
    /**
     * 显示搜索结果
     */
    private void showSearchResults() {
        progressBar.setVisibility(View.GONE);
        recyclerViewResults.setVisibility(View.VISIBLE);
        emptyState.setVisibility(View.GONE);
        addFriendMethods.setVisibility(View.GONE);
        contactsSection.setVisibility(View.GONE);
    }
    
    /**
     * 显示空状态
     */
    private void showEmptyState() {
        progressBar.setVisibility(View.GONE);
        recyclerViewResults.setVisibility(View.GONE);
        emptyState.setVisibility(View.VISIBLE);
        addFriendMethods.setVisibility(View.GONE);
        contactsSection.setVisibility(View.GONE);
    }
    
    /**
     * 显示添加好友方式
     */
    private void showAddFriendMethods() {
        progressBar.setVisibility(View.GONE);
        recyclerViewResults.setVisibility(View.GONE);
        emptyState.setVisibility(View.GONE);
        addFriendMethods.setVisibility(View.VISIBLE);
        contactsSection.setVisibility(View.GONE);
    }
    
    /**
     * 显示联系人部分
     */
    private void showContactsSection() {
        progressBar.setVisibility(View.GONE);
        recyclerViewResults.setVisibility(View.GONE);
        emptyState.setVisibility(View.GONE);
        addFriendMethods.setVisibility(View.GONE);
        contactsSection.setVisibility(View.VISIBLE);
    }
    
    @Override
    public void onResultClick(Contact contact) {
        // 打开好友申请页面
        Intent intent = new Intent(this, FriendRequestActivity.class);
        intent.putExtra("contact", contact);
        startActivity(intent);
    }
    
    @Override
    public void onAddClick(Contact contact) {
        // 打开好友申请页面
        Intent intent = new Intent(this, FriendRequestActivity.class);
        intent.putExtra("contact", contact);
        startActivity(intent);
    }
    
    /**
     * 发送好友请求
     */
    private void sendFriendRequest(Contact contact) {
        Toast.makeText(this, "正在发送好友请求给：" + contact.getName(), Toast.LENGTH_SHORT).show();
        
        // 显示加载状态
        progressBar.setVisibility(View.VISIBLE);
        
        // 获取当前用户ID
        Long currentUserId = sessionManager.getCurrentUserId();
        if (currentUserId == null) {
            Toast.makeText(this, "无法获取当前用户信息，请重新登录", Toast.LENGTH_SHORT).show();
            progressBar.setVisibility(View.GONE);
            return;
        }
        // 构建好友请求数据
        Map<String, Object> requestData = new HashMap<>();
        Map<String, Object> requesterMap = new HashMap<>();
        Map<String, Object> addresseeMap = new HashMap<>();
        // 设置请求者（当前用户）
        requesterMap.put("id", currentUserId);
        requestData.put("requester", requesterMap);
        // 设置接收者（要添加的好友）
        try {
            // 尝试将联系人ID解析为Long
            Long addresseeId = Long.parseLong(contact.getId());
            addresseeMap.put("id", addresseeId);
        } catch (NumberFormatException e) {
            // 如果联系人ID不是数字格式，可能需要通过其他方式（如账号）获取用户ID
            // 这里使用模拟ID，实际应用中应先查询用户ID
            addresseeMap.put("id", 0);
            Log.e(TAG, "联系人ID格式不正确: " + contact.getId(), e);
        }
        requestData.put("addressee", addresseeMap);
        
        // 添加请求备注
        requestData.put("requesterNote", "你好，我是" + sessionManager.getUserName());
        
        // 发送API请求
        String url = apiService.getCurrentBaseUrl() + "/api/friendships/mobile";
        Log.d(TAG, "发送好友请求: " + url);
        
        RequestBody requestBody = RequestBody.create(
                MediaType.parse("application/json; charset=utf-8"),
                new Gson().toJson(requestData));
        
        Request request = new Request.Builder()
                .url(url)
                .header("Authorization", "Bearer " + sessionManager.getAuthToken())
                .post(requestBody)
                .build();
        
        OkHttpClient client = new OkHttpClient();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e(TAG, "发送好友请求失败: " + e.getMessage(), e);
                runOnUiThread(() -> {
                    progressBar.setVisibility(View.GONE);
                    Toast.makeText(AddFriendActivity.this, "发送请求失败，请稍后重试", Toast.LENGTH_SHORT).show();
                });
            }
            
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String responseBody = response.body().string();
                Log.d(TAG, "好友请求响应: " + responseBody);
                
                runOnUiThread(() -> {
                    progressBar.setVisibility(View.GONE);
                    
                    if (response.isSuccessful()) {
                        Toast.makeText(AddFriendActivity.this, 
                                "好友请求已发送，等待对方验证", Toast.LENGTH_LONG).show();
                        
                        // 更新UI状态，禁用添加按钮
                        if (adapter != null) {
                            adapter.updateAddButtonStatus(contact.getId(), SearchResultAdapter.STATUS_REQUEST_SENT);
                        }
                    } else {
                        Toast.makeText(AddFriendActivity.this, 
                                "发送请求失败: " + response.code(), Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
    }
    
    /**
     * 设置状态栏
     */
    private void setStatusBar() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {// 设置状态栏文字和图标为深色
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
            getWindow().setStatusBarColor(getResources().getColor(android.R.color.white));// 设置状态栏颜色为白色
        }
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_CONTACTS_PERMISSION) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {// 已经直接显示了联系人页面，这里只是记录权限状态
                Log.d(TAG, "通讯录权限已被授予");
                Toast.makeText(this, "已获得通讯录权限", Toast.LENGTH_SHORT).show();
            } else {
                Log.d(TAG, "通讯录权限被拒绝");// 不显示任何提示，因为已经显示了联系人页面
            }
        }
    }
} 